/**
 * 超级管理员功能路由
 */

var router = require('express').Router();
var userTool = require('../bin/user');
var articleTool = require('../bin/article');
var dbentityTool = require('../bin/dbentity');
var redisentityTool = require('../bin/redisentity');
var assertAlljs = require('../bin/util/assert-alljs');
var ObjectID = require('mongodb').ObjectID;
var fs = require('fs');

var sendmail = require('../bin/driver/sendmail');
router.get('/admin(.*)?', async function(req, res){
    let assert = assertAlljs(req, res);
    let checkMessage = userTool.check(req.session.user);
    if (await assert(checkMessage))
        return;
    res.render('dyn.admin.html');
});

router.post('/testmail', async function(req, res) {
    let assert = assertAlljs(req, res);
    let checkMessage = userTool.check(req.session.user, {role:'admin'});
    if (await assert(checkMessage))
        return;

    sendmail('aelue@126.com', '来自alljs的测试邮件', '<div style="padding:2% 5%"><p><h1>欢迎来到alljs</h1></p><p><a href="http://localhost:3000">进入首页</a></p></div>');
    await req.session.pushMessage('邮件已发送');
    req.behavior.set('aelue@126.com');
    res.redirect('back');
});

var sms = require('../bin/driver/sms');
router.post('/testsms', async function(req, res) {
    let assert = assertAlljs(req, res);
    let checkMessage = userTool.check(req.session.user, {role:'admin'});
    if (await assert(checkMessage))
        return;

    sms('15920372250', '1', ['1234', '1']);
    //sms('15920372250,13450224593', '1', ['1234', '1']);
    await req.session.pushMessage('短信已发送');
    req.behavior.set('15920372250');
    res.redirect('back');
});

router.post('/setadmin', async function(req, res){
    let user = req.session.user;
    let assert = assertAlljs(req, res);
    let checkMessage = userTool.check(user);
    if (await assert(checkMessage))
        return;

    let result = await dbentityTool.updateOne('user', {"_id":ObjectID(user._id)}, {"$set":{'role':'admin'}});
    if (await assert(result instanceof Error))
        return;

    user.role = 'admin';
    await req.session.pushMessage('已升级为管理员');
    res.redirect('back');
});

router.post('/setguest', async function(req, res){
    let user = req.session.user;
    let assert = assertAlljs(req, res);
    let checkMessage = userTool.check(user, {role:'admin'});
    if (await assert(checkMessage))
        return;

    let result = await dbentityTool.updateOne('user', {"_id":ObjectID(user._id)}, {"$unset":{'role':''}});
    if (await assert(result instanceof Error))
        return;

    delete user.role;
    await req.session.pushMessage('已降级为普通用户');
    res.redirect('back');
});

router.post('/deleteusers', async function(req, res){
    let assert = assertHttp(req, res);
    let checkMessage = userTool.check(req.session.user, {role:'admin'});
    if (await assert(checkMessage))
        return;

    let result = await dbentityTool.deleteMany('user', {group:{ $ne: 'testgroup' }});
    if (await assert(result instanceof Error))
        return;

    await req.session.signout();
    req.behavior.set('testgroup');
    res.end('all users(without testgroup) deleted');
});

router.post('/cleanuparticle', async function(req, res){
    let assert = assertAlljs(req, res);
    let checkMessage = userTool.check(req.session.user, {role:'admin'});
    if (await assert(checkMessage))
        return;
    let result = await articleTool.cleanupArticle();
    await assert(true, result instanceof Error ? '清理文章出错: ' + result.message : '清理文章成功');
});

router.post('/resetarticletxt', async function(req, res){
    let assert = assertAlljs(req, res);
    let checkMessage = userTool.check(req.session.user, {role:'admin'});
    if (await assert(checkMessage))
        return;
    let files = fs.readdirSync('data/html');
    let len = '.html'.length;
    for (let file of files){
        if (file.substr(file.length-len) === '.html'){
            let id = file.substr(0, file.length-len);
            let content = fs.readFileSync('data/html/'+file).toString();
            require('../bin/article').saveContentText(id, content);
        }
    }
    await assert(true, '重设文章txt检索文件成功');
});

router.post('/deletesession', async function(req, res){
    let assert = assertAlljs(req, res);
    let checkMessage = userTool.check(req.session.user, {role:'admin'});
    if (await assert(checkMessage))
        return;

    let keys1 = await redisentityTool.findIds('ses');
    if (keys1 instanceof Array){
        for (let seskey of keys1)
            await redisentityTool.set('ses', seskey, null);
    }
    let keys2 = await redisentityTool.findIds('sso');
    if (keys2 instanceof Array){
        for (let ssokey of keys1)
            await redisentityTool.set('sso', ssokey, null);
    }

    res.end('all session deleted');
});

router.post('/shutdownserver', async function(req, res){
    let assert = assertAlljs(req, res);
    let checkMessage = userTool.check(req.session.user, {role:'admin'});
    if (await assert(checkMessage))
        return;
    
    res.end('server closed');
    req.behavior.save();
    await req.behavior.flushToDB();
    process.exit(0);
});

module.exports = router;